import { Injectable } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import { RedisService } from '../redis/redis.service'
import { SendCodeDto } from './dto/comm.dto';


@Injectable()
export class CommService {
  constructor(private readonly redisService: RedisService) { }
  /**
   * ! 发送验证码
   * @param email 邮箱
   * @param type 验证码类型 register-注册/forget-重置密码
   */
  async sendEmail(body: SendCodeDto) {
    const { email, type } = body;
    // 生成验证码
    const code = Math.floor(1000 + Math.random() * 9000)
    // 存储验证码到 Redis
    const REDIS_KEY = `${type}:${email}`

    // 发送验证码
    try {
      // 校验验证码是否在短时间内重复发送
      const existingCode = await this.redisService.getCode(REDIS_KEY);
      if (existingCode) {
        throw new Error('该邮箱已发送验证码，请五分钟后重试');
      }

      const transporter = nodemailer.createTransport({
        host: process.env.EMAIL_HOST || 'smtp.qq.com',
        port: Number(process.env.EMAIL_PORT) || 465,
        secure: true, // use SSL if required
        auth: {
          user: process.env.EMAIL_USERNAME || '123456@qq.com',
          pass: process.env.EMAIL_PASSWORD || 'cndxdfrkwcvrcdaj',
        },
      });
      // 发送邮件
      const info = await transporter.sendMail({
        from: `"${process.env.EMAIL_TITLE || '时屿科技工作室'}" <${process.env.EMAIL_USERNAME || '123456@qq.com'}>`,
        to: email,
        subject: '验证码',
        html: `<p>您的验证码是：<strong style="font-size:24px;color:red;">${code}</strong></p>
             <p>有效期5分钟，请尽快使用。</p>`
      })
      // 打印发送结果
      console.log('Email sent:', info.messageId);
      // 校验发送结果
      if (info.messageId) {

        this.redisService.setCode(REDIS_KEY, code.toString(), 5 * 60)
        return {
          code: 200,
          message: 'Email sent successfully',
        };
      }
    }
    catch (error) {
      return {
        code: 500,
        message: error.message,
      };
    }
  }
}
